package Servlets;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.PasswordAuthentication;
import javax.mail.Session; 
import javax.mail.Transport; 
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;  
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import ServerDB.User;

/**
 * Servlet :: sending an email with password to user email
 * @author Guy & Liel
 *
 */
public class SendPasswordServlet  extends HttpServlet
{
	
	//NOTE: we using two session, the first is of Hibernate and the second is for session of email
	private static final long serialVersionUID = 1L;
	/**
	 * doPost sending an email -> send user name in request
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
	{
		User user = null;
		// ...
		
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out=response.getWriter();
		out.println("<HTML>");
		out.println("<HEAD>");
		System.out.println("Check sending password");
		String userName=request.getParameter("UserNameTextBox").toString();
		File file=new File("C:\\ourDropBox\\hibernate.cfg.xml");
		SessionFactory sessionFactory=new Configuration().configure(file).buildSessionFactory();
		org.hibernate.classic.Session sessionHibernate=sessionFactory.openSession();
		String strQuery="FROM User e WHERE e.userName=:userNameQry";
		Query query=sessionHibernate.createQuery(strQuery);
		query.setParameter("userNameQry", userName);
		System.out.println("After SQL line");
		@SuppressWarnings("unchecked")
		List<User> listUsers=query.list();
		Iterator<User> itUser=listUsers.iterator();
		
		
		
		 	         
		if(itUser.hasNext())//Response The user name is in DataBase
		{
		
		user=itUser.next();
		// Recipient's email ID needs to be mentioned.
		String to =user.getEmail();
		
		// Sender's email ID needs to be mentioned
		String from = "GL.CleverDropBox@gmail.com";
		
		//Properties
		Properties properties = new Properties();
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.socketFactory.port", "465");
		properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.port", "465");

		Session session = Session.getDefaultInstance(properties,new Authenticator()
		{
			protected PasswordAuthentication getPasswordAuthentication() 
			{
			      return new PasswordAuthentication("GL.CleverDropBox@gmail.com", "GUYLIEL12");
			}
		});
		try
		{
			// Create a default MimeMessage object.
			MimeMessage message = new MimeMessage(session);
			// Set From: header field of the header.
			message.setFrom(new InternetAddress(from));
			// Set To: header field of the header.
			message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
			// Set Subject: header field
			message.setSubject(userName+"'s password");
			// Now set the actual message
			message.setText("Dear "+userName +"\n"+"Your password is "+user.getPassword());
			// Send message
			Transport.send(message);
			
			System.out.println("Sent message successfully....");
			HttpSession httpSession=request.getSession(true);
			httpSession.setAttribute("sending password email", "sending password email");
			out.println("<meta HTTP-EQUIV='REFRESH' content='0; url=forgotYouPass.jsp'>");

		}
		catch (MessagingException mex) 
		{
		     mex.printStackTrace();
		}

		}		
		else//User name dosen't exist
		{
			
			System.out.println("User name not exist");
			HttpSession httpSession=request.getSession(true);
			httpSession.setAttribute("error user name", "error user name not exist");
			out.println("<meta HTTP-EQUIV='REFRESH' content='0; url=forgotYouPass.jsp'>");
		}
		
		out.println("</HEAD>");
		out.println("<BODY>");
		out.println("</BODY>");
		out.println("</HTML>");
		out.close();
		
	}
		
}
